package com.hlg.xboot.service;

import com.hlg.xboot.config.AppConfig;
import com.hlg.xboot.exceptions.ParameterException;
import com.digi_zones.common.utils.CommonUtils;
import com.digi_zones.common.utils.RegexpUtils;
import com.hlg.xboot.utils.SMSHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Description: 短信服务接口 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 * <p>myblog: http://blog.csdn.net/xyang81</p>
 *
 * @author 杨信
 * @version 1.0
 * @date 2016/11/1
 */
@Component
public class SMSService {

    /**
     * 发送短信
     * @param phone 接收短信的手机
     * @param type 短信类型
     * @return
     * @throws Exception
     */
    @Autowired
    private com.digi_zones.common.aliyun.sms.SMSService smsService;
    @Autowired
    private SMSHelper smsHelper;
    @Autowired
    private AppConfig appConfig;

    public boolean sendSMS(String phone, Integer type) throws Exception {
        String smsTemplate = appConfig.getAliyun().getSms().getTemplates().get(type);
        if (smsTemplate == null) {
            throw new ParameterException("无效的短信类型");
        }

        if (!RegexpUtils.checkMobile(phone)) {
            throw new ParameterException("无效的手机号码.");
        }

        String code = smsHelper.getSmsVerifyCode(phone);    // 先取出之前生成的验证码，如果还有效，则继续使用
        if (StringUtils.isEmpty(code)) {
            code = CommonUtils.genRandomNumSeq(6);          // 生成短信验证码
        }

        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        params.put("product", appConfig.getAliyun().getSms().getProductName());

        boolean result = smsService.sendSmsWithDsm(phone, smsTemplate, params);
        if (result) {
            smsHelper.saveSmsVerifyCode(phone, code);
        }
        return result;
    }

}
